package com.ywh.floating

import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
import com.ywh.floating.lifecycle.FloatingActivityLifecycle
import com.ywh.floating.lifecycle.IFloatingAttach

/**
 * Create by yangwenhao on 2022/8/5
 */
@SuppressLint("StaticFieldLeak")
object FloatingWindow {
    internal var mConfig: FloatingConfig? = null
    private var mActivityLifecycle: FloatingActivityLifecycle? = null
    private var mFloatingManager: IFloatingAttach? = null
    private var mContext: Context? = null

    fun init(showNow: Boolean? = true, builderAction: FloatingConfig.Builder.() -> Unit) {
        mConfig = FloatingConfig.Builder().apply(builderAction).build()
        mFloatingManager?.setFloatingConfig(mConfig)
        if (showNow == true) {
            mActivityLifecycle?.weakReference?.get()?.apply {
                mFloatingManager?.attach(this)
            }
        }
    }

    fun close() {
        mConfig = null
        mFloatingManager?.close()
//        (mContext as? Application)?.apply {
//            unregisterActivityLifecycleCallbacks(mActivityLifecycle)
//        }
//        mActivityLifecycle = null
        mContext = null
    }

    internal fun initActivityLifecycle(context: Context) {
        mContext = context
        if (mFloatingManager == null) {
            mFloatingManager = FloatingManager
        }
        if (mActivityLifecycle == null) {
            mActivityLifecycle = FloatingActivityLifecycle(mFloatingManager)
        }
        (context as Application).apply {
            unregisterActivityLifecycleCallbacks(mActivityLifecycle)
            registerActivityLifecycleCallbacks(mActivityLifecycle)
        }
    }
}